package example.step2;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.ArrayList;

/**
 * @description:
 * @className: Person
 * @package: example.step1
 */
public class WriteReplacePerson implements Serializable {

    private String name;
    private int age;

    public WriteReplacePerson(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return name + "(" + age + ")";
    }

    private Object writeReplace() throws ObjectStreamException {
        ArrayList<Object> list = new ArrayList<>();
        list.add(name);
        list.add(age);
        return list;
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // 错！写了也没用
        ArrayList<Object> list = (ArrayList)in.readObject();
        this.name = (String)list.get(0);
        this.age = (int)list.get(1);
    }

    public static void print(String s) {
        System.out.println(s);
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:\\idea-workspace\\gitee\\demo\\serializable\\src\\main\\java\\objfile\\writeReplacePerson.obj"))) {
            WriteReplacePerson p = new WriteReplacePerson("lala", 33);
            oos.writeObject(p);
            oos.close();
        }
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("E:\\idea-workspace\\gitee\\demo\\serializable\\src\\main\\java\\objfile\\writeReplacePerson.obj"))) {
            print(((ArrayList)ois.readObject()).toString());
        }
    }


}
